
import sys

try:
	import psycopg2.psycopg1 as psyco
except Exception, e:
	print "Erro ao importar psycopg2", e.__str__()
	sys.exit(0)

type_dict = {
		'_abstime': 1023,
		'_aclitem': 1034,
		'_bit': 1561,
		'_bool': 1000,
		'_box': 1020,
		'_bpchar': 1014,
		'_bytea': 1001,
		'_char': 1002,
		'_cid': 1012,
		'_cidr': 651,
		'_circle': 719,
		'_date': 1182,
		'_float4': 1021,
		'_float8': 1022,
		'_inet': 1041,
		'_int2': 1005,
		'_int2vector': 1006,
		'_int4': 1007,
		'_int8': 1016,
		'_interval': 1187,
		'_line': 629,
		'_lseg': 1018,
		'_macaddr': 1040,
		'_money': 791,
		'_name': 1003,
		'_numeric': 1231,
		'_oid': 1028,
		'_oidvector': 1013,
		'_path': 1019,
		'_point': 1017,
		'_polygon': 1027,
		'_refcursor': 2201,
		'_regclass': 2210,
		'_regoper': 2208,
		'_regoperator': 2209,
		'_regproc': 1008,
		'_regprocedure': 2207,
		'_regtype': 2211,
		'_reltime': 1024,
		'_text': 1009,
		'_tid': 1010,
		'_time': 1183,
		'_timestamp': 1115,
		'_timestamptz': 1185,
		'_timetz': 1270,
		'_tinterval': 1025,
		'_varbit': 1563,
		'_varchar': 1015,
		'_xid': 1011,
		'abstime': 702,
		'aclitem': 1033,
		'any': 2276,
		'anyarray': 2277,
		'bit': 1560,
		'bool': 16,
		'box': 603,
		'bpchar': 1042,
		'bytea': 17,
		'char': 18,
		'cid': 29,
		'cidr': 650,
		'circle': 718,
		'cstring': 2275,
		'date': 1082,
		'float4': 700,
		'float8': 701,
		'inet': 869,
		'int2': 21,
		'int2vector': 22,
		'int4': 23,
		'int8': 20,
		'internal': 2281,
		'interval': 1186,
		'language_handler': 2280,
		'line': 628,
		'lseg': 601,
		'macaddr': 829,
		'money': 790,
		'name': 19,
		'numeric': 1700,
		'oid': 26,
		'oidvector': 30,
		'opaque': 2282,
		'path': 602,
		'point': 600,
		'polygon': 604,
		'record': 2249,
		'refcursor': 1790,
		'regclass': 2205,
		'regoper': 2203,
		'regoperator': 2204,
		'regproc': 24,
		'regprocedure': 2202,
		'regtype': 2206,
		'reltime': 703,
		'smgr': 210,
		'text': 25,
		'tid': 27,
		'time': 1083,
		'timestamp': 1114,
		'timestamptz': 1184,
		'timetz': 1266,
		'tinterval': 704,
		'trigger': 2279,
		'unknown': 705,
		'varbit': 1562,
		'varchar': 1043,
		'void': 2278,
		'xid': 28
}
	
class DB:
	
	def __init__(self):
		pass

	def connect(self, *args):

		dns = []

		for k in ['dbname', 'host', 'user', 'password', 'port']:
			if args[0].get(k):
				dns.append("%s='%s'" % (k, args[0][k]))

		try:
			self.conn = psyco.connect(' '.join(dns))
			self.conn.autocommit(True)
			self.cur = dbcur(self.conn.cursor(), True)

			self.conn1 = psyco.connect(''.join(dns))
			self.dbcur = dbcur(self.conn1.cursor(), False)

			return True
		except Exception, e:
			raise e

	def cursor(self):
		return self.dbcur

	def __getattr__(self, attname):
		return getattr(self.cur, attname)

class dbcur:
	
	def __init__(self, cur, autocommit=False):

		self.cur = cur
		self.autocommit = autocommit

	def get_attnames(self, table):

		r = []
		if table:
			sql = "select * from %s limit 0" % table
			self.cur.execute(sql)
			desc = self.cur.description
			for d in list(desc):
				n = d[0]
				if n == 'grid': continue
				type = None
				for k, v in type_dict.items():
					if d[1] == v:
						type = k
						break
				r.append((n, type))

		return r

	def commit(self):
		self.execute('commit')

	def rollback(self):
		self.execute('rollback')

	def execute(self, sql=""):
		print "SQL EXECUTE: %s" % sql
		self.cur.execute(sql)

	def get_list_result(self, sql):
		print "SQL LISTRESULT: %s" % sql
		self.cur.execute(sql)
		return self.cur.fetchall()

	def get_dict_result(self, sql):
		print "SQL DICTRESULT: %s" % sql
		self.cur.execute(sql)
		return self.cur.dictfetchall()

	def get_first_result(self, sql, default=None):
		print "SQL FIRSTRESULT: %s" % sql
		self.cur.execute(sql)
		ret = self.cur.fetchone()
		if not ret is None:
			if len(ret) == 1:
				ret = ret[0]

		if ret is None:
			return default
		else:
			return ret
